#include <stdlib.h>

#include "dexsession.h"

#include <QDir>
#include <QProcess>
#include <QSettings>
#include <QX11Info>

#include <X11/Xlib.h>

DexSession::DexSession(int &argc, char **argv) : QApplication(argc, argv)
	{
		setenv("DESKTOP_SESSION", "DexiosDE", true);
		startProcesses();
	}

DexSession::~DexSession()
	{
		logout();
	}

//void DexSession::removeProcess(int exitCode, QProcess::ExitStatus exitStatus)
//	{
//		foreach (QProcess *process, processes)
//		{
//			if (process->exitCode() == exitCode && process->exitStatus() == exitStatus)
//				processes.take(processes.key(process))->deleteLater();
//		}
//
//		if (processes.count() == 0)
//			quit();
//	}

void DexSession::startProcesses()
	{
		QSettings session(QSettings::IniFormat, QSettings::UserScope, "TrueFusion", "DexSession");
		QStringList defaultList = (QStringList() << "openbox" << "Dextop" << "DexPanel");
		QStringList programs = session.value("StartUp/programs", QVariant(defaultList)).toStringList();
		foreach (QString program, programs)
		{
			qDebug() << program;
//			QProcess *process = new QProcess(this);
//			processes.insert(program, process);
//			process->start(program, QProcess::NotOpen);
//			process->waitForStarted(2000);
//			process->waitForReadyRead(500); // just here to waste time.

//			connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(removeProcess(int,QProcess::ExitStatus)));
			qint64 pId;
			QStringList args;
			QProcess::startDetached(program, args, QDir::homePath(), &pId);
			procIds.insert(program, pId);
			sleep(1);
		}
	}

void DexSession::logout()
	{
//		disconnect(this, SLOT(removeProcess(int,QProcess::ExitStatus)));
//		foreach (QProcess *process, processes)
//		{
//			process->close();
//			process->waitForFinished(10000);
//			processes.take(processes.key(process))->deleteLater();
//
//			if (processes.count() == 0)
//				quit();
//		}

		foreach (qint64 proc, procIds)
		{
			QString p(QString("kill -15 ")+QString::number(proc));
			system(p.toUtf8().data());
		}
	}
